package com.conan.dailyflickr.app;

import java.lang.ref.WeakReference;
import java.util.HashMap;

import android.app.Application;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class DailyFlickrApplication extends Application{

	private final String TAG = "App";
	private static Context mContext;

	private HashMap<String, WeakReference<Context>> contextObjects = 
        new HashMap<String, WeakReference<Context>>();

    public synchronized Context getActiveContext(String className) {
        WeakReference<Context> ref = contextObjects.get(className);
        if (ref == null) {
            return null;
        }

        final Context c = ref.get();
        if (c == null) // If the WeakReference is no longer valid, ensure it is removed.
            contextObjects.remove(className);

        return c;
    }

    public synchronized void setActiveContext(String className, Context context) {
        WeakReference<Context> ref = new WeakReference<Context>(context);
        this.contextObjects.put(className, ref);
    }

    public synchronized void resetActiveContext(String className) {
        contextObjects.remove(className);
    }
    
	@Override
    public void onCreate() {
		Log.d(TAG, ">>> [APP] going to Create!");
    	super.onCreate();
        mContext = this;
	}
	
	public static Context getCustomAppInstance() {
		return mContext;
	}
	
	@Override
	public void onTerminate() {
		Log.d(TAG, ">>> [APP] going to Terminate!");
		super.onTerminate();
	}
	
	@Override
	public void onLowMemory() {
		Log.w(TAG, ">>> [APP] low in memory attend!"); 
		super.onLowMemory();
	}
	
	private static Toast mToast;
	/** Show toast message */
	public static void makeToastMessage(final String message) {
		if (mToast == null) {
			mToast = Toast.makeText(mContext, message, /*LENGTH_SHORT*/0);
			mToast.show();
		} else {
			mToast.setText(message);
			mToast.cancel();
			mToast.show();
		}
	}

}
